import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JScrollPane;

public class Hanoi extends JFrame {

	private JPanel contentPane;
	private JTextField textOrder;
	private JTextArea textAnswer;
	private int times = 0;
	String answer = "";

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Hanoi frame = new Hanoi();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public Hanoi() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 439);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);

		JLabel lblOrder = new JLabel("Order:");
		lblOrder.setBounds(14, 13, 54, 18);
		contentPane.add(lblOrder);

		JButton btnMove = new JButton("Answer");
		btnMove.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				showAnswer();
			}
		});
		btnMove.setBounds(305, 9, 113, 27);
		contentPane.add(btnMove);

		textOrder = new JTextField();
		textOrder.setBounds(64, 10, 227, 24);
		contentPane.add(textOrder);
		textOrder.setColumns(10);

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(14, 44, 404, 335);
		contentPane.add(scrollPane);

		textAnswer = new JTextArea("Input the order then click Answer!");
		scrollPane.setViewportView(textAnswer);
		textAnswer.setEditable(false);
	}

	protected void showAnswer() {
		textAnswer.setText("");
		if (textOrder.getText().length() < 1) {
			textAnswer.setText("Input an num as order!");
			return;
		}
		int order;
		try {
			order = Integer.parseInt(textOrder.getText());
		} catch (Exception e) {
			textAnswer.setText("Input an num as order!");
			return;
		}
		this.getHanoiAnswer(order, 'x', 'y', 'z');
		textAnswer.setText(answer);
	}

	private void getHanoiAnswer(int panel, char x, char y, char z) {
		if (panel == 1) {
			this.movePanel(x, panel, z);
		} else {
			getHanoiAnswer(panel - 1, x, z, y);
			movePanel(x, panel, z);
			getHanoiAnswer(panel - 1, y, x, z);
		}
	}

	private String movePanel(char before, int panel, char after) {
		String step = ++times + "times,move " + panel + " panel from " + before + " to " + after + "\n";
		this.answer = this.answer + step;
		return step;
	}
}
